<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);

class Products extends OC_Controller 
{

	protected $path_img_upload_folder;
    protected $path_img_thumb_upload_folder;
    protected $path_url_img_upload_folder;
    protected $path_url_img_thumb_upload_folder;
    protected $delete_img_url;

	function __construct() {
		parent::__construct();
		$this->load->helper(array('form', 'url'));
		$this->load->model('products/product_model', 'pdm');
		$this->load->model('products/category_model', 'ctm');
		$this->load->model('products/sub_category_model', 'sctm');
		$this->upload_path = OC_FRONT_DIR . 'ocimages' . DS . 'products/thumbnail2' . DS;

		$this->setPath_img_upload_folder(OC_FRONT_DIR."ocimages/products/");
        $this->setPath_img_thumb_upload_folder(OC_FRONT_DIR."ocimages/products/thumbnail/");
        $this->setDelete_img_url('');
        $this->setPath_url_img_upload_folder("products/product_upload/appimage/products/");
        $this->setPath_url_img_thumb_upload_folder("products/product_upload/appimage/products/thumbnail/");
	}
	
	function _remap($method, $params = array()) {
		parent::_remap($method, $params);
		
		if (method_exists($this, $method)) return call_user_func_array(array(
			$this,
			$method
		), $params);
		else show_404();
	}

	function init_header() {
		$this->header['jeasyui'] 		= TRUE;
		$this->header['categories'] 	= $this->ctm->get_all()->rows;
		$this->header['subcategories'] 	= $this->sctm->get_all()->rows;
		
		$this->header['source_top'] = array(
			link_tag(site_url('products/themescript/uploader/css/jquery.fileupload.css')) ,
			link_tag(site_url('products/themescript/uploader/css/jquery.fileupload-ui.css'))
		);
		
		$this->header['source_bot'] = array(
			script_tag(site_url('products/themescript/uploader/js/load-image.js')),
			script_tag(site_url('products/themescript/uploader/js/canvas-to-blob.js')),
			script_tag(site_url('products/themescript/uploader/js/tmpl.js')),
			script_tag(site_url('products/themescript/uploader/js/vendor/jquery.ui.widget.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.iframe-transport.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.fileupload.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.fileupload-process.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.fileupload-image.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.fileupload-validate.js')),
			script_tag(site_url('products/themescript/uploader/js/jquery.fileupload-ui.js')),
			script_tag(site_url('products/themescript/jquery.number.js')),
			script_tag(site_url('products/themescript/app/products.js'))
		);
	}

	function index() {
		$this->init_header();
		
		$this->header['nav'] = 'catalog';
		$this->header['pagetitle'] = 'Products';
		
		$this->view('products/product_view');
	}
	
	function load_data() {
		$params = $this->input->post();
		$result = $this->pdm->get_all($params);
				
		print (json_encode($result));
	}
	
	function load_categories() {
		$params = $this->input->post();
		$result = $this->ctm->get_all($params);
		$nodes = array();
		if (count($result->rows) > 0) {
			foreach ($result->rows as $row) {
				$nodes[] = array(
					'id' => $row->c_id,
					'text' => $row->c_caption_en
				);
			}
		}
		print (json_encode($nodes));
	}

	function load_images($product_id) {
		$images = $this->pdm->get_images($product_id);
		$params['images'] = count($images) > 0 ? array_chunk($images, 3) : $images;
		
		print ($this->load->view('products/galery_view', $params, TRUE));
	}

	function save_data() {
		$post = $this->input->post();

		if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])) {
			$name = $_FILES['userfile']['name'];
        	$name = is_array($name) ? $name[0] : $name;

        	$name = strtr($name, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
        	$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);

	        $config['upload_path'] = $this->getPath_img_upload_folder();
	        $config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
		    $config['encrypt_name'] = TRUE;

        	$this->load->library('upload', $config);
			
			if ($this->do_upload())
	        {
	            $data = $this->upload->data();
	            $name = $data['file_name'];

	            $config['new_image'] 		= $this->getPath_img_thumb_upload_folder();
	            $config['image_library'] 	= 'gd2';
	            $config['source_image'] 	= $this->getPath_img_upload_folder() . $name;
	            $config['create_thumb'] 	= FALSE;
	            $config['maintain_ratio'] 	= TRUE;
	            $config['width'] 			= 240;
	            $config['height'] 			= 270;

	            $this->load->library('image_lib', $config);
	            $this->image_lib->resize();

	            /* Second size */    
				$configSize2['image_library']   = 'gd2';
				$configSize2['source_image']    =  $this->getPath_img_upload_folder() . $name;
				$configSize2['create_thumb']    = FALSE;
				$configSize2['maintain_ratio']  = TRUE;
				$configSize2['width']           = 448;
				$configSize2['height']          = 360;
				$configSize2['new_image']   	= $this->upload_path;

				$this->image_lib->initialize($configSize2);
				$this->image_lib->resize();
				$this->image_lib->clear();

	            $post['p_filename'] = $data['file_name'];
				$post['p_fileorig'] = $data['orig_name'];
	        }
			/*$this->load->library('upload', array(
				'upload_path' => $this->upload_path,
				'allowed_types' => 'jpg|gif|png|bmp|JPG|GIF|PNG|BMP',
				'encrypt_name' => true
			));
			
			if ($this->upload->do_upload()) {
				$uploaded = $this->upload->data();
				$post['p_filename'] = $uploaded['file_name'];
				$post['p_fileorig'] = $uploaded['orig_name'];
			}*/

		}
		//unset($post['files']);

		if (empty($post['p_id'])) {
			$post['p_created_date'] = date('Y-m-d H:i:s');
			unset($post['p_id']);
			$this->pdm->add($post);
		} else {
			$post['p_modified_date'] = date('Y-m-d H:i:s');
			$this->pdm->edit($post, array(
				'p_id' => $post['p_id']
			));
		}

		print(json_encode(array(
			'success' => TRUE
		)));
	}
	
	function simple_update() {
		$post = $this->input->post(null, true);
		$success = $this->pdm->edit($post, array(
			'p_id' => $post['p_id']
		));
		print (json_encode(array(
			'success' => $success
		)));
	}
	
	function delete_data() {
		$post = $this->input->post();
		
		if ($this->pdm->delete(array(
			'p_id' => $post['p_id']
		))) {
			$this->pdm->delete(array(
				'p_id' => $post['p_id']
			));
			$this->pdm->delete_img(array(
				'pi_p_id' => $post['p_id']
			));
		}
		
		print (json_encode(array(
			'success' => TRUE
		)));
	}
	
	function delete_image() {
		$keys = $this->input->post();
		$this->pdm->delete_img($keys);
		print (json_encode(array(
			'success' => TRUE
		)));
	}
	
	public function reset_slug() {
		$this->db->join('products_properties b', 'p_id=pp_p_id', 'inner');
		$qry = $this->db->get('products a');
		$row = $qry->result_array();
		
		foreach ($row as $k => $v) {
			$this->db->set('p_slug', slugify($v['p_name'] . ' ' . $v['pp_color']));
			$this->db->where('p_id', $v['p_id']);
			$this->db->update('products');
		}
	}

	public function do_upload()
    {
        if ( ! $this->upload->do_upload())
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public function deleteImage()
    {
        //Get the name in the url
        $file = $this->uri->segment(3);

        $success = unlink($this->getPath_img_upload_folder() . $file);
        $success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);

        //info to see if it is doing what it is supposed to 
        $info = new stdClass();
        $info->sucess = $success;
        $info->path = $this->getPath_url_img_upload_folder() . $file;
        $info->file = is_file($this->getPath_img_upload_folder() . $file);
        if (IS_AJAX)
        {//I don't think it matters if this is set but good for error checking in the console/firebug
            echo json_encode(array($info));
        }
        else
        {
            //here you will need to decide what you want to show for a successful delete
            var_dump($file);
        }
    }


    //Load the files
    public function get_files()
    {
        $this->get_scan_files();
    }

    //Get info and Scan the directory
    public function get_scan_files()
    {
        $file_name = isset($_REQUEST['file']) ?
                basename(stripslashes($_REQUEST['file'])) : null;
        if ($file_name)
        {
            $info = $this->get_file_object($file_name);
        }
        else
        {
            $info = $this->get_file_objects();
        }
        header('Content-type: application/json');
        echo json_encode($info);
    }

    protected function get_file_object($file_name)
    {
        $file_path = $this->getPath_img_upload_folder() . $file_name;
        if (is_file($file_path) && $file_name[0] !== '.')
        {

            $file = new stdClass();
            $file->name = $file_name;
            $file->size = filesize($file_path);
            $file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
            $file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
            //File name in the url to delete 
            $file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
            $file->delete_type = 'DELETE';

            return $file;
        }
        return null;
    }

    //Scan
    protected function get_file_objects()
    {
        return array_values(array_filter(array_map(
            array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
        )));
    }



    // GETTER & SETTER 
    public function getPath_img_upload_folder()
    {
        return $this->path_img_upload_folder;
    }

    public function setPath_img_upload_folder($path_img_upload_folder)
    {
        $this->path_img_upload_folder = $path_img_upload_folder;
    }

    public function getPath_img_thumb_upload_folder()
    {
        return $this->path_img_thumb_upload_folder;
    }

    public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder)
    {
        $this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
    }

    public function getPath_url_img_upload_folder()
    {
        return $this->path_url_img_upload_folder;
    }

    public function setPath_url_img_upload_folder($path_url_img_upload_folder)
    {
        $this->path_url_img_upload_folder = $path_url_img_upload_folder;
    }

    public function getPath_url_img_thumb_upload_folder()
    {
        return $this->path_url_img_thumb_upload_folder;
    }

    public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder)
    {
        $this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
    }

    public function getDelete_img_url()
    {
        return $this->delete_img_url;
    }

    public function setDelete_img_url($delete_img_url)
    {
        $this->delete_img_url = $delete_img_url;
    }
	
}

/* End of file products.php */
/* Location: ./applications/module_admin/products/controllers/products.php */